package com.centaline.androidsalesblog.activities.sale;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.FootPrintActivity;
import com.centaline.androidsalesblog.activities.search.SaleSearchActivity;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.base.BaseListMapActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.list.EsfEstateListFragment;
import com.centaline.androidsalesblog.fragments.listmap.EsfEstateListMapFragment;
import com.centaline.androidsalesblog.iml.DropCompleteListener;
import com.centaline.androidsalesblog.iml.RefreshListener;
import com.centaline.androidsalesblog.model.businissobject.DropBo;
import com.centaline.androidsalesblog.model.databaseobject.SearchDo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centaline.androidsalesblog.rx.database.DropSaleRegionFunc1;
import com.centaline.androidsalesblog.rx.database.MetroFunc1;
import com.centaline.androidsalesblog.rx.database.NewEstSearchDataFunc1;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.DropUtil;
import com.centaline.androidsalesblog.widgets.ListSearchView;
import com.centaline.androidsalesblog.widgets.dropdown.SalePriceDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SingleDrop;
import com.centaline.androidsalesblog.widgets.dropdown.TrebleDrop;
import com.centanet.framework.interfaces.IResponseListener;

import java.util.ArrayList;
import java.util.Locale;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func3;
import rx.schedulers.Schedulers;

/**
 * 小区列表
 */
public class EsfEstateListActivity extends BaseListMapActivity {

    private TrebleDrop trebleDrop;
    private SalePriceDrop salePriceDrop;
    private SingleDrop singleDrop;

    private EsfEstateListFragment esfEstateListFragment;
    private EsfEstateListMapFragment esfEstateListMapFragment;

    private EsfEstateListApi esfEstateListApi;

    @Override
    protected void findViews() {
        setUniversalToolbar();
        super.findViews();
    }

    @Override
    protected void initViews() {
        super.initViews();
        esfEstateListApi = new EsfEstateListApi(EsfEstateListActivity.class, EsfEstateListRo.class,
                new IResponseListener<EsfEstateListRo>() {
                    @Override
                    public void onResponse(EsfEstateListRo esfEstateListRo) {
                        esfEstateListFragment.stopRefresh(esfEstateListRo.getList());
                        esfEstateListMapFragment.setMapArrayList(esfEstateListRo.getList(), esfEstateListApi.getStartIndex() == 0);
                        if (esfEstateListApi.getStartIndex() == 0) {
                            snack(esfEstateListRo.getTotal() == 0 ?
                                    getString(R.string.snack_esf_nothing) :
                                    String.format(Locale.CHINA, getString(R.string.snack_esf), esfEstateListRo.getTotal()));
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        esfEstateListFragment.refreshError();
                        netWorkUnable();
                    }
                });
    }

    @Override
    protected boolean setShowFab() {
        return false;
    }

    @Override
    protected BaseFragment getFragment1() {
        esfEstateListFragment = new EsfEstateListFragment();
        esfEstateListFragment.setRefreshListener(new RefreshListener() {
            @Override
            public void down() {
                esfEstateListApi.setStartIndex(0);
                if (needLocation) {
                    startLocation();
                } else {
                    requestList();
                }
            }

            @Override
            public void up(int count) {
                esfEstateListApi.setStartIndex(count);
                requestList();
            }
        });
        return esfEstateListFragment;
    }

    @Override
    protected BaseFragment getFragment2() {
        esfEstateListMapFragment = new EsfEstateListMapFragment();
        return esfEstateListMapFragment;
    }

    @Override
    protected void initDrop() {
        dropDownView.initTabs(R.array.esfEstate);
        trebleDrop = new TrebleDrop(dropDownView, this);
        salePriceDrop = new SalePriceDrop(dropDownView, this);
        singleDrop = new SingleDrop(dropDownView, this);
        dropDownView.addDrops(trebleDrop, salePriceDrop, singleDrop);
        dropDownView.setDropCompleteListener(new DropCompleteListener() {
            @Override
            public void complete(int position, boolean fromMore, int type, DropBo... dropBos) {
                int size = dropBos == null ? 0 : dropBos.length;
                switch (type) {
                    case 10://区域
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("R");
                        if (size == 1) {
                            if (DropUtil.compareValue(dropBos[0])) {
                                resetTab(position);
                                setTab(position, "区域");
                            } else {
                                esfEstateListApi.setScopeId(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                                baiduEvent("J1_4_Value", dropBos[0].getText());
                            }
                            downRefresh(false,true);
                        } else if (size == 2) {
                            esfEstateListApi.setScopeId(dropBos[0].getValue());
                            if (DropUtil.compareValue(dropBos[1])) {
                                setTab(position, dropBos[0].getText());
                                baiduEvent("J1_4_Value", dropBos[0].getText());
                            } else {
                                esfEstateListApi.setScopeId(dropBos[1].getValue());
                                setTab(position, dropBos[1].getText());
                                baiduEvent("J1_4_Value", dropBos[1].getText());
                            }
                            downRefresh(false,true);
                        }
                        break;
                    case 11://附近
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("F");
                        if (size == 2) {
                            esfEstateListApi.setRound(dropBos[1].getValue());
                            setTab(position, dropBos[1].getText());
                            downRefresh(true);
                            baiduEvent("J1_4_Value", dropBos[1].getText());
                        }
                        break;
                    case 20://地铁
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("S");
                        if (size == 1) {
                            if (DropUtil.compareValue(dropBos[0])) {
                                resetTab(position);
                                setTab(position, "地铁");
                            } else {
                                esfEstateListApi.setSubwayid(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                                baiduEvent("J1_4_Value", dropBos[0].getText());
                            }
                            downRefresh(false,true);
                        } else if (size == 2) {
                            esfEstateListApi.setSubwayid(dropBos[0].getValue());
                            if (DropUtil.compareValue(dropBos[1])) {
                                setTab(position, dropBos[0].getText());
                                baiduEvent("J1_4_Value", dropBos[0].getText());
                            } else {
                                esfEstateListApi.setStationid(dropBos[1].getValue());
                                setTab(position, dropBos[1].getText());
                                baiduEvent("J1_4_Value", dropBos[1].getText());
                            }
                            downRefresh(false,true);
                        }
                        break;
                    case 30://均价
                        if (size == 1) {
                            String value = dropBos[0].getValue();
                            if (TextUtils.isEmpty(value)) {
                                esfEstateListApi.setMin("");
                                esfEstateListApi.setMax("");
                                resetTab(position);
                                downRefresh(false);
                            } else if (value.contains(",")) {
                                String[] values = value.split(",");
                                esfEstateListApi.setMin(values[0]);
                                esfEstateListApi.setMax(values[1]);
                                setTab(position, dropBos[0].getText());
                                downRefresh(false);
                                baiduEvent("J1_5_Value", dropBos[0].getText());
                            }
                        } else if (size == 2) {
                            esfEstateListApi.setMin(dropBos[0].getValue());
                            esfEstateListApi.setMax(dropBos[1].getValue());
                            setTab(position, DropUtil.customPrice(dropBos[0], dropBos[1]));
                            baiduEvent("J1_5_Value", DropUtil.customPrice(dropBos[0], dropBos[1]));
                            downRefresh(false);
                        }
                        break;
                    case 100://排序
                        if (size == 1) {
                            if (TextUtils.isEmpty(dropBos[0].getValue())) {
                                esfEstateListApi.setSort("");
                                resetTab(position);
                            } else {
                                esfEstateListApi.setSort(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                                baiduEvent("J1_6_Value",dropBos[0].getText());
                            }
                            downRefresh(false);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        Observable.combineLatest(RxDataBase.getSaleRegions()
                        .subscribeOn(Schedulers.io())
                        .map(new DropSaleRegionFunc1()),
                RxDataBase.nearby(),
                RxDataBase.getMetro()
                        .subscribeOn(Schedulers.io())
                        .map(new MetroFunc1()),
                new Func3<ArrayList<DropBo>, DropBo, ArrayList<DropBo>, ArrayList<DropBo>>() {
                    @Override
                    public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, DropBo nearBy, ArrayList<DropBo> dropBos3) {
                        final ArrayList<DropBo> list = new ArrayList<>();
                        DropBo dropBo = new DropBo(10);
                        dropBo.setText("区域");
                        dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.setChildrenList(new ArrayList<DropBo>());
                        DropBo dropBo1 = new DropBo(10);
                        dropBo1.setText(CommonConstant.DROP_TEXT_NO_LIMITED);
                        dropBo1.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.getChildrenList().add(dropBo1);
                        if (AppConstant.NearbyEnable) {
                            dropBo.getChildrenList().add(nearBy);
                        }
                        dropBo.getChildrenList().addAll(dropBos);
                        list.add(dropBo);
                        dropBo = new DropBo(20);
                        dropBo.setText("地铁");
                        dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.setChildrenList(dropBos3);
                        list.add(dropBo);
                        return list;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        trebleDrop.init(dropBos);
                    }
                });
        RxDataBase.getSearchData("EsfAvgPrice")
                .map(new NewEstSearchDataFunc1(30))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        salePriceDrop.init(dropBos);
                    }
                });
        ArrayList<DropBo> orderBy = new ArrayList<>();
        DropBo dropBo = new DropBo(100);
        dropBo.setText("智能排序");
        dropBo.setValue("");
        orderBy.add(dropBo);
        dropBo = new DropBo(100);
        dropBo.setText("均价从低到高");
        dropBo.setValue("2");
        orderBy.add(dropBo);
        dropBo = new DropBo(100);
        dropBo.setText("均价从高到低");
        dropBo.setValue("3");
        orderBy.add(dropBo);
        singleDrop.init(orderBy);
    }

    @Override
    protected ListSearchView.SearchCallback getSearchCallback() {
        return new ListSearchView.SearchCallback() {
            @Override
            public void clear() {
                esfEstateListApi.reset();
                resetTab(0);
                downRefresh(false);
            }

            @Override
            public void gotoSearch() {
                startActivityForResult(new Intent(EsfEstateListActivity.this, SaleSearchActivity.class)
                                .putExtra(ExtraConstant.SearchType, 60)
                        , CommonConstant.REQ_SEARCH);
                baiduEvent("J1_1_Click");
            }

            @Override
            public void gotoSearchVoice() {
                startActivityForResult(new Intent(EsfEstateListActivity.this, SaleSearchActivity.class)
                                .putExtra(ExtraConstant.SearchVoice, true)
                                .putExtra(ExtraConstant.SearchType, 60)
                        , CommonConstant.REQ_SEARCH);
                baiduEvent("J1_2_Click");
            }
        };
    }

    @Override
    protected void downRefresh(boolean needLocation, boolean clearLocation) {
        this.needLocation = needLocation;
        if (clearLocation) {
            esfEstateListFragment.setLocation(null);
        }
        esfEstateListFragment.startRefresh();
    }

    public void requestList() {
        esfEstateListApi.startRequest();
    }

    /**
     * 重置标签
     *
     * @param position 位置
     */
    private void resetTab(int position) {
        dropDownView.resetTab(position);
    }

    /**
     * 设置标签
     *
     * @param position 位置
     * @param tab      文本
     */
    protected void setTab(int position, String tab) {
        dropDownView.setTab(position, tab);
    }

    @Override
    protected void locationInfo(BDLocation bdLocation) {
        switch (bdLocation.getLocType()) {
            case 61:
            case 161:
                LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                esfEstateListFragment.setLocation(latLng);
                esfEstateListApi.setLatLng(latLng);
                requestList();
                break;
            default:
                esfEstateListFragment.setLocation(null);
                esfEstateListApi.setLatLng(null);
                esfEstateListApi.setRound("");
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                startActivity(new Intent(this, FootPrintActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_SEARCH:
                    SearchDo searchDo = data.getParcelableExtra(ExtraConstant.SearchObject);
                    if (searchDo != null) {
                        String category = searchDo.getCategory();
                        if ("region".equalsIgnoreCase(category) ||
                                "block".equalsIgnoreCase(category)) {
                            setSearchContent(searchDo.getTitle());
                            esfEstateListApi.reset();
                            esfEstateListApi.setScopeId(searchDo.getCode());
                            downRefresh(false);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
